<template>
  <div class="client-add">
    <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
      <template #footer>
        <a-space>
          <a-button @click="router.back()">
            <template #default>取消</template>
          </a-button>
          <a-button
            v-if="taskData.form.state !== 4"
            type="primary"
            @click="submit"
          >
            <template #default>执行</template>
          </a-button></a-space
        >
      </template>
      <div class="base-info"
        ><TitleBox title="基本信息"></TitleBox>
        <div class="base-info-header"
          ><a-form style="width: 60%" :model="taskData" auto-label-width>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item field="posts.post2" label="采购任务单号:"
                  ><a-input
                    style="width: 400px"
                    v-model="taskData.form.number"
                    disabled
                /></a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="posts.post2" label="任务下达时间："
                  ><a-date-picker
                    style="width: 400px"
                    v-model="taskData.form.createdAt"
                    disabled
                /></a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="posts.post2" label="任务下达人:"
                  ><a-input
                    style="width: 400px"
                    disabled
                    v-model="taskData.form.createByName"
                    placeholder=""
                    allow-clear
                /></a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="posts.post2" label="需求交付时间："
                  ><a-date-picker
                    style="width: 400px"
                    disabled
                    v-model="taskData.form.beginTime"
                /></a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="posts.post2" label="优先级：">
                  <div
                    :class="
                      taskData.form.priority === 4
                        ? 'Urgent'
                        : taskData.form.priority === 3
                        ? 'Tall'
                        : taskData.form.priority === 1
                        ? 'low'
                        : 'centre'
                    "
                    >{{
                      taskData.form.priority === 4
                        ? '紧急'
                        : taskData.form.priority === 3
                        ? '高'
                        : taskData.form.priority === 1
                        ? '低'
                        : '中'
                    }}</div
                  >
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <TitleBox title="执行信息"></TitleBox>
        <div class="base-info-header"
          ><a-form style="width: 60%" :model="taskData.form" auto-label-width>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="posts.post2" label="任务负责人："
                  ><a-input
                    style="width: 400px"
                    disabled
                    v-model="taskData.form.executeByName"
                    allow-clear
                /></a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="posts.post2" label="任务开始时间："
                  ><a-date-picker
                    v-model="taskData.form.beginTime"
                    placeholder="系统自动生成"
                    style="width: 400px"
                    disabled
                /></a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="posts.post2" label="任务结束时间："
                  ><a-date-picker
                    style="width: 400px"
                    v-model="taskData.form.endTime"
                    :disabled="
                      taskData.form.state === 3 || taskData.form.state === 4
                    "
                /></a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="posts.post2" label="执行状态：">
                  <div
                    :class="
                      taskData.form.state === 1
                        ? 'Qualified'
                        : taskData.form.state === 2
                        ? 'Qualified'
                        : taskData.form.state === 3
                        ? 'Examining'
                        : taskData.form.state === 4
                        ? 'Pass'
                        : ''
                    "
                  >
                    <span>
                      {{
                        taskData.form.state === 1
                          ? '待确认'
                          : taskData.form.state === 2
                          ? '待执行'
                          : taskData.form.state === 3
                          ? '执行中'
                          : taskData.form.state === 4
                          ? '已完成'
                          : ''
                      }}
                    </span>
                  </div>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <TitleBox title="采购明细"
          ><template #buts v-if="taskData.form.state > 2"
            ><a-button type="primary" @click="batchBuildOrder()"
              >创建采购订单</a-button
            ></template
          ></TitleBox
        >
        <div class="base-info-header">
          <a-table
            row-key="id"
            :row-selection="rowSelection"
            v-model:selectedKeys="selectedKeys"
            @select="onSelect"
            @select-all="onSelectAll"
            :scroll="scroll"
            :data="taskData.form.product"
            :pagination="false"
            :stripe="true"
            style="width: 100%"
            :bordered="{
              headerCell: true,
            }"
          >
            <template #columns>
              <a-table-column :width="80" align="center">
                <template #title> 序号 </template>
                <template #cell="{ record, rowIndex }">
                  <div style="position: relative">
                    <div>{{ rowIndex + 1 }}</div>
                    <div
                      v-if="taskData.form.state <= 2"
                      style="position: absolute; top: 7px; right: 7px"
                      @click="addNewProduct(record, rowIndex)"
                    >
                      <i class="iconfont icon-chaifenzuhe"></i>
                    </div>
                  </div>
                </template>
              </a-table-column>
              <a-table-column
                align="center"
                :width="150"
                title="产品名称"
                data-index="name"
              >
              </a-table-column>
              <a-table-column
                align="center"
                :width="150"
                title="产品编码"
                data-index="number"
              >
              </a-table-column>

              <a-table-column
                align="center"
                :width="150"
                title="产品规格"
                data-index="spec"
              >
              </a-table-column>
              <a-table-column
                align="center"
                title="计划数量"
                data-index="planAmount"
                :width="150"
              >
              </a-table-column>
              <a-table-column :width="80" align="center">
                <template #title> 状态 </template>
                <template #cell="{ record }">
                  <a-typography-text disabled v-if="record.state === 1">
                    待创建
                  </a-typography-text>
                  <a-typography-text type="primary" v-if="record.state === 2">
                    执行中
                  </a-typography-text>
                  <a-typography-text type="success" v-if="record.state === 3">
                    已完成
                  </a-typography-text>
                  <a-typography-text type="warning" v-if="record.state === 4">
                    异常完成
                  </a-typography-text>
                </template>
              </a-table-column>
              <a-table-column
                align="center"
                :width="80"
                title="操作"
                data-index="spec"
                v-if="taskData.form.state !== 1 && taskData.form.state !== 2"
              >
                <template #cell="{ record }">
                  <a-button
                    type="text"
                    :disabled="record.state > 1"
                    @click="buildSingleOrder(record)"
                    >创建采购订单
                  </a-button>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>
        <TitleBox title="订单信息" v-if="taskData.form.state > 2"></TitleBox>
        <div class="base-info-header" v-if="taskData.form.state > 2">
          <OrderResp :tableData="orderRespData"></OrderResp>
        </div>
      </div>
    </pageHeader>
  </div>
  <selectSupplier
    v-model:visible="isSelectSupplier"
    :code="SupplierProductCode"
    @awardedSupplier="awardedSupplier"
  ></selectSupplier>

  <a-modal
    v-if="isSupplierVisible"
    v-model:visible="isSupplierVisible"
    @ok="splitHandleOk"
    @cancel="handleCancel"
  >
    <template #title> 拆分数量 </template>
    <div
      >拆分数量：<a-input-number
        :min="1"
        :style="{ width: '320px' }"
        v-model="splitAmount"
        :max="copyRecord.planAmount"
    /></div>
  </a-modal>
</template>

<script lang="ts" setup>
  import {
    reactive,
    ref,
    computed,
    onMounted,
    defineAsyncComponent,
  } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import {
    getPurchasetaskDetail,
    putTaskPurchasetask,
    postTaskPurchasetask,
    putTaskPurchasetaskList,
  } from '@/api/buy-management/buy-task/index';
  import { cloneDeep } from 'lodash';
  import { getPurchaseProductNumber } from '@/api/buy-management/buy-material/index';
  import { Message } from '@arco-design/web-vue';
  import { useBuyStore } from '@/store';
  import selectSupplier from './select-supplier/index.vue';

  let OrderResp = defineAsyncComponent(
    () => import('./components/order-resp/index.vue')
  );
  const router = useRouter();
  const orderRespData = ref();
  const store = useBuyStore();
  const SupplierProductCode = ref();
  const isSupplierVisible = ref(false);
  const isDisabled = ref(false);
  const route = useRoute();
  const tableRef = ref();
  const title: string = '采购任务详情';
  const breadCrumb: string[] = ['采购管理', '采购任务', '采购任务详情'];
  const id = Number(route.query.id);

  let rowSelection = {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  };
  const scroll = {
    x: 2000,
  };
  const bordered = {
    headerCell: true,
  };

  let taskData = reactive<any>({
    form: {},
  });
  const isSelectSupplier = ref(false);

  const getTaskData = async () => {
    const res = await getPurchasetaskDetail({ id });
    taskData.form = res.taskData;
    taskData.form.product.forEach(async (item: any) => {
      if (item.state > 1) item.disabled = true;
      if (taskData.form.state === 1 || taskData.form.state === 2) {
        const res = await getPurchaseProductNumber({ number: item.number });
        let markSupplier = res.filter((i: any) => i.mark === 1);
        console.log(11, markSupplier);
        if (!markSupplier) markSupplier = res;
        item.supplierName = markSupplier[0].supplierName;
        item.supplierId = markSupplier[0].supplierId;
        item.guidePrice = markSupplier[0].singlePrice;
        item.totalPrice = markSupplier[0].singlePrice * item.amount;
        item.guidePriceUnit = '人民币';
      }
    });
    isDisabled.value = taskData.form.product.every((i) => i.state === 2);
    orderRespData.value = res.orderResp ? res.orderResp : [];
  };
  getTaskData();

  const createBut = ref();

  const selectrowIndex = ref();
  const copyRecord = ref();
  const getSupplierName = (record: any, rowIndex: number) => {
    isSelectSupplier.value = true;
    // copyRecord.value = { ...record };
    SupplierProductCode.value = record.number;
    selectrowIndex.value = rowIndex;
  };
  const awardedSupplier = async (data: any) => {
    const { supplierId, supplierName, singlePrice, singleUint } = data[0];
    const { planAmount } = taskData.form.product[selectrowIndex.value];
    taskData.form.product[selectrowIndex.value].supplierId = supplierId;
    taskData.form.product[selectrowIndex.value].supplierName = supplierName;
    taskData.form.product[selectrowIndex.value].guidePrice = singlePrice;
    taskData.form.product[selectrowIndex.value].totalPrice =
      planAmount * singlePrice;
    taskData.form.product[selectrowIndex.value].totalPriceUnit = singleUint;
  };

  const cgeDiscount = async (record: any) => {
    if (record.discount) {
      let msg = ref(0);
      msg.value = (100 - record.discount) / 100;
      const newMsg = record.guidePrice * record.planAmount;
      record.totalPrice = newMsg * msg.value;
    } else {
      record.totalPrice = record.guidePrice * record.planAmount;
      record.discount = 0;
    }
  };

  const rowSelectionCopy = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });

  const selectedKeys = ref([]);
  const selectedList: any = ref([]);

  const columns = [
    {
      title: '物料编码',
      code: 'number',
    },
    {
      title: '物料名称',
      code: 'name',
    },
    {
      title: '型号规格',
      code: 'spec',
    },
    {
      title: '物料指导单价',
      code: 'singlePrice',
    },
    {
      title: '采购单位',
      code: 'PurchaseUnitName',
    },
    {
      title: '供应商编号',
      code: 'supplierNumber',
    },
    {
      title: '供应商名称',
      code: 'supplierName',
    },
    {
      title: '供应商级别',
      code: 'supplierLevelName',
    },
    {
      title: '产品认证情况',
      code: 'authState',
    },
    {
      title: '是否有关联采购合同',
      code: 'contract',
    },
  ];

  const data = ref([]);
  // 获取数据
  const getData = async (number: any) => {
    const res = await getPurchaseProductNumber({ number });
    data.value = res;
  };

  const splitAmount = ref();
  const addNewProduct = (record: any) => {
    isSupplierVisible.value = true;
    copyRecord.value = record;
    splitAmount.value = 0;
  };

  const CgePriceUnit = async (e: string, key: string, record: any) => {
    record.key = e;
    await putTaskPurchasetask({ ...record });
  };

  const buildSingleOrder = (record: any) => {
    // const { supplierId, supplierName, totalPrice } = record;
    // record.taskProductId = record.id;
    // delete record.id;
    // store.CreateOrder = {
    //   supplierId,
    //   supplierName,
    //   totalPrice,
    //   Product: [{ ...record }],
    // };
    // if (sessionStorage.getItem('store')) {
    //   sessionStorage.removeItem('store');
    // }
    console.log(record);

    store.CreateOrder = {
      Product: [{ ...record }],
    };
    router.push({
      name: 'AddOrderPurchaseList',
    });
    router.push({
      name: 'AddOrderPurchaseList',
    });
  };

  // const isBatchBuildOrder = () => {
  //   return taskData.form.product.every((ele: any) => ele.state > 1);
  // };

  const batchBuildOrder = () => {
    const msg = selectedList.value.every(
      (item: any) => item.supplierId === selectedList.value[0].supplierId
    );
    if (!msg) {
      Message.error('供应商不一致，无法创建订单');
    } else {
      let msg: any = ref({
        supplierId: selectedList.value[0].supplierId,
        supplierName: selectedList.value[0].supplierName,
        totalPrice: 0,
        Product: [],
      });
      selectedList.value.forEach((item: any, index: number) => {
        msg.value.Product.push({
          ...item,
          taskProductId: item.id,
        });
        delete item.id;
      });
      for (let i = 0; i < msg.value.Product.length; i += 1) {
        msg.value.totalPrice += msg.value.Product[i].totalPrice;
      }
      store.CreateOrder = msg.value;
      router.push({
        name: 'AddOrderPurchaseList',
      });
    }
  };

  const submit = async () => {
    taskData.form.endTime = new Date(taskData.form.endTime).toJSON();
    if (route.query.state === '2') {
      taskData.form.state = 4;
      await putTaskPurchasetaskList({
        ...taskData.form,
        taskProduct: taskData.form.product,
      });
      router.back();
    } else {
      // let isSelectSupplier = taskData.form.product.every((i) => i.supplierId);
      // if (!isSelectSupplier) {
      //   Message.error('请选择供应商！');
      // } else {
      taskData.form.state = 3;
      await putTaskPurchasetaskList({
        ...taskData.form,
        taskProduct: taskData.form.product,
      });
      router.back();
      // }
    }
  };

  const splitHandleOk = () => {
    let msg = cloneDeep(copyRecord.value);
    msg.planAmount = splitAmount.value;
    msg.supplierId = undefined;
    msg.supplierName = '';
    msg.guidePrice = undefined;
    msg.totalPrice = undefined;
    msg.totalPriceUnit = '';
    delete msg.id;
    taskData.form.product.push({ ...msg });
    copyRecord.value.planAmount -= splitAmount.value;
    isSupplierVisible.value = false;
  };

  // 选择数据事件
  const onSelect = (rowKeys: any, rowKey: any, record: any) => {
    const index = selectedList.value.findIndex((item: any) => {
      return item.id === rowKey;
    });
    if (index === -1) {
      selectedList.value.push(record);
      selectedKeys.value.push(record.id);
    } else {
      selectedList.value.splice(index, 1);
    }
  };

  // 全选按钮
  const onSelectAll = (checked: boolean) => {
    if (checked) {
      selectedList.value = cloneDeep(taskData.form.product);
    } else {
      selectedList.value = [];
    }
  };
</script>

<style scoped lang="less">
  .client-add {
    .base-info {
      padding: 10px 40px 10px 40px;

      .avatar {
        position: absolute;
        width: 100px;
      }
      &-header {
        // padding: 0 100px;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        // :deep(.arco-form-item-content-flex) {
        //   display: block;
        //   line-height: 32px;
        //   color: #cccccc29;
        // }
      }

      &-extra {
        .contact-info,
        .invoice-info,
        .client-info,
        .remarks-info {
          padding: 0 100px;
        }
      }
    }
  }

  // .report-item {
  //   width: 95%;
  //   height: 60px;
  //   margin: auto;
  //   background-color: rgba(245, 247, 250);
  //   line-height: 60px;
  // }

  .custom-radio-card {
    padding: 10px 16px;
    border: 1px solid var(--color-border-2);
    border-radius: 4px;
    width: 150px;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    height: 40px;
    line-height: 40px;
    display: flex;
  }

  .custom-radio-card-masky {
    height: 17px;
    width: 17px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 100%;
    border: 1px solid var(--color-border-2);
    box-sizing: border-box;
    margin-left: 30%;
  }

  .custom-radio-card-maskn {
    height: 17px;
    width: 17px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 100%;
    border: 1px solid var(--color-border-2);
    box-sizing: border-box;
    margin-left: 30%;
  }

  .custom-radio-card-mask-dot {
    width: 8px;
    height: 8px;
    border-radius: 100%;
  }

  .custom-radio-card-title {
    color: var(--color-text-1);
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 8px;
  }

  .custom-radio-card-shade {
    width: 45px;
    height: 38px;
    border-right: 1px solid var(--color-border-2);
    background-color: white;
    box-sizing: border-box;
  }

  .custom-radio-card-shadey {
    width: 105px;
    height: 38px;
    background-color: white;
    box-sizing: border-box;
  }

  .custom-radio-card-shaden {
    width: 105px;
    height: 38px;
    background-color: white;
    box-sizing: border-box;
  }

  .custom-radio-card-checked .custom-radio-card-masky {
    border-color: rgb(49, 194, 124);
  }

  .custom-radio-card-checked .custom-radio-card-maskn {
    border-color: rgb(255, 153, 0);
  }

  .custom-radio-card-checked .custom-radio-card-shadey {
    // background-color: var(--color-primary-light-1);
    // ba-color: rgb(49, 194, 124);
    color: white;
    background-color: rgb(49, 194, 124);
  }

  .custom-radio-card-checked .custom-radio-card-shaden {
    // background-color: var(--color-primary-light-1);
    // ba-color: rgb(49, 194, 124);
    color: white;
    background-color: rgb(255, 153, 0);
  }

  .custom-radio-card:hover .custom-radio-card-title,
  .custom-radio-card-checked .custom-radio-card-title {
    color: rgb(var(--primary-6));
  }

  .custom-radio-card-checked .custom-radio-card-mask-dot {
    background-color: rgb(var(--primary-6));
  }

  .WaitSubmitted {
    // 待下达
    width: 95px;
    height: 40px;
    border-radius: 100px;
    line-height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #c9cdd4;
    color: rgb(255, 255, 255);
    border: none;
  }

  .Examining {
    // 执行中
    width: 95px;
    height: 40px;
    border-radius: 100px;
    line-height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #165dff;
    border: none;
    color: aliceblue;
  }

  .Pass {
    // 已通过
    width: 95px;
    height: 40px;
    border-radius: 100px;
    line-height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(49, 194, 124);
    border: none;
    color: aliceblue;
  }

  .NoPass {
    //不通过
    width: 95px;
    height: 40px;
    border-radius: 100px;
    line-height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f53f3f;
    border: none;
  }

  .Qualified {
    // 待执行
    width: 95px;
    height: 40px;
    border-radius: 100px;
    line-height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255, 247, 232);
    border: none;
    color: #ff9a2e;
  }

  .Urgent {
    width: 73px;
    height: 40px;
    background: inherit;
    border-radius: 5px;
    border-width: 1px;
    border-style: solid;
    box-shadow: none;
    font-size: 16px;
    border-color: rgba(255, 0, 0, 1);
    background-color: rgba(255, 236, 232, 1);
    color: #f53f3f;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .low {
    width: 73px;
    height: 40px;
    background: inherit;
    border-radius: 5px;
    border-width: 1px;
    border-style: solid;
    box-shadow: none;
    font-size: 16px;
    border-color: #b3b3b3;
    background-color: #cccccc62;
    color: #b3b3b3;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .centre {
    width: 73px;
    height: 40px;
    background: inherit;
    border-radius: 5px;
    border-width: 1px;
    border-style: solid;
    box-shadow: none;
    font-size: 16px;
    border-color: #ff7d00;
    background-color: #ff7b0073;
    color: #ff7d00;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .Tall {
    width: 73px;
    height: 40px;
    background: inherit;
    border-radius: 5px;
    border-width: 1px;
    border-style: solid;
    box-shadow: none;
    font-size: 16px;
    border-color: #ff7d00;
    background-color: rgba(255, 236, 232, 1);
    color: #ff7d00;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  // :deep(.arco-input-wrapper),
  // :deep(.arco-input[disabled]) {
  //   -webkit-text-fill-color: rgb(0, 0, 0);
  // }

  // :deep(.arco-picker-disabled),
  // :deep(.input[disabled]) {
  //   -webkit-text-fill-color: rgb(0, 0, 0);
  // }

  .order-info {
    width: 95%;
    margin: 20px auto;
  }

  .box {
    padding-top: 10px;
    margin-top: 20px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
    width: 100%;
  }
</style>
